import AuthComponent from '@/components/Authorized/AuthComponent';
import React, { useState, useEffect, useRef } from 'react';
import { Table, DatePicker, Select, Button, Modal, message, Radio } from 'antd';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';

import { connect } from 'dva';
import MyNormForm from './MyNormForm';

import styles from './index.less';
import {
  getNormHeavyLuggageList,
  addNormHeavyLuggage,
  delNormHeavyLuggageItem,
  updateNormHeavyLuggage,
} from '../../service';

function NormTable({ placeSelectData }) {
  const actionRef = useRef();

  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [selectedRows, setselectedRows] = useState([]);
  const [editModalMsg, seteditModalMsg] = useState({ show: false, type: '', formItems: {} });

  const { run: addNormHeavyLuggageHandle } = useRequest(params => addNormHeavyLuggage(params), {
    manual: true,
    onSuccess: res => {
      seteditModalMsg({ ...editModalMsg, show: false, formItems: {}, type: '' });
      reloadTable();
      message.success('新增成功');
    },
  });

  const { run: delNormHeavyLuggageItemHandle } = useRequest(
    params => delNormHeavyLuggageItem(params),
    {
      manual: true,
      onSuccess: res => {
        seteditModalMsg({ ...editModalMsg, show: false, formItems: {}, type: '' });
        reloadTable();
        message.success('删除成功');
      },
    },
  );
  const { run: updateNormHeavyLuggageHandle } = useRequest(
    params => updateNormHeavyLuggage(params),
    {
      manual: true,
      onSuccess: res => {
        seteditModalMsg({ ...editModalMsg, show: false, formItems: {}, type: '' });
        reloadTable();
        message.success('修改成功');
      },
    },
  );

  const classTypeMap = {
    A: '合并舱位',
    J: '经济舱',
    G: '公务舱',
  };
  const columns = [
    {
      title: '始发地',
      dataIndex: 'orgPlace',
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select showSearch style={{ width: '100%' }} {...rest}>
            {placeSelectData.map(item => (
              <Select.Option key={item.value} value={item.value}>
                {item.label}
              </Select.Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '到达地',
      dataIndex: 'dstPlace',
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select showSearch style={{ width: '100%' }} {...rest}>
            {placeSelectData.map(item => (
              <Select.Option key={item.value} value={item.value}>
                {item.label}
              </Select.Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '舱位类型',
      dataIndex: 'classType',
      hideInSearch: true,
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select style={{ width: '100%' }} {...rest}>
            <Select.Option value="A">合并舱位</Select.Option>
            <Select.Option value="J">经济舱</Select.Option>
            <Select.Option value="G">公务舱</Select.Option>
          </Select>
        );
      },
      render: (target, row, index, allData) => {
        return (
          <div>
            {
              row.aoOverWeightClassList.length > 1 ? '区分舱等' : '不区分舱等'
            }
            {/* {row.aoOverWeightClassList.length > 1
              ? classTypeMap.A
              : (row.aoOverWeightClassList[0] &&
                  row.aoOverWeightClassList[0].classType &&
                  classTypeMap[row.aoOverWeightClassList[0].classType]) ||
                target} */}
          </div>
        );
      },
    },
  ];
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setselectedRowKeys(selectedRowKeys);
      setselectedRows(selectedRows);
    },
  };

  const addHandle = () => {
    seteditModalMsg({ show: true, type: 'add', formItems: {} });
  };

  const editHandle = () => {
    if (selectedRows.length !== 1) {
      message.error('编辑操作需要勾选数据并且只能勾选一项');
      return;
    }
    seteditModalMsg({ show: true, type: 'update', formItems: selectedRows[0] });
  };

  const delHandle = () => {
    let ids = [];
    for (const item of selectedRows) {
      for (const item2 of item.aoOverWeightClassList) {
        ids.push(item2.id);
      }
    }
    // let ids = selectedRows.map(item => item.id);
    if (ids.length > 0) {
      Modal.confirm({
        title: '提示',
        content: `确认删除选中的数据吗？`,
        onOk: () => {
          delNormHeavyLuggageItemHandle(ids);
        },
      });
    } else {
      message.error('删除操作需要勾选数据');
    }
  };
  const reloadTable = ()=>{
    setselectedRowKeys([]);
    actionRef.current.reload();
  }

  const closeModal = () => {
    // actionRef.current.reload();
    seteditModalMsg({ show: false, formItems: {} });
  };
  const expandedRowRender = row => {
    const sonColumns = [
      {
        title: '舱等类型',
        dataIndex: 'classType',
        render: (value, row, index) => <div>{classTypeMap[value]}</div>,
      },
      {
        title: '超件标准',
        dataIndex: 'aoOverNumber',
        render: (value, row, index) => {
          let data = [
            value.overNumberFirstPrice,
            value.overNumberSecondPrice,
            value.overNumberThirdPrice,
          ].filter(item => item);
          return data.map((item, sonIndex) => {
            return (
              <div key={sonIndex}>
                <span>第{sonIndex + 1}件</span>
                <span>{item}CNY/件</span>
              </div>
            );
          });
        },
      },
      {
        title: '超尺寸标准',
        dataIndex: 'aoOverSize',
        render: (value, row, index) => (
          <div>
            <span>
              {value.overSizeMinValue}-{value.overSizeMaxValue}cm
            </span>
            <span style={{ marginLeft: '10px' }}>{value.overSizePrice}CNY/件</span>
          </div>
        ),
      },
      {
        title: '超重标准',
        dataIndex: 'aoOverWeightList',
        render: (value, row, index) =>
          value.map((item, itemIndex) => {
            return (
              <div key={itemIndex}>
                <span>
                  {item.overWeightMinValue}-{item.overWeightMaxValue}kg
                </span>
                <span style={{ marginLeft: '10px' }}>{item.overWeightPrice}CNY/件</span>
              </div>
            );
          }),
      },
    ];
    let sonData = row.aoOverWeightClassList;
    return <Table rowKey="id" columns={sonColumns} dataSource={sonData} pagination={false} />;
  };
  const editSava = (type, data) => {
    if (type === 'add' || type === 'copyAdd') {
      addNormHeavyLuggageHandle(data);
    } else {
      updateNormHeavyLuggageHandle(data);
    }
  };
  const copyaddHandle = () => {
    if (selectedRows.length !== 1) {
      message.error('拷贝并新建操作需要勾选数据并且只能勾选一项');
      return;
    }
    seteditModalMsg({ show: true, type: 'copyAdd', formItems: selectedRows[0] });
  };
  return (
    <>
      <Modal
        title={editModalMsg.type === 'update' ? '修改' : '新建'}
        visible={editModalMsg.show}
        footer={null}
        closable={false}
        width="80%"
        onCancel={closeModal}
      >
        <div>
          <MyNormForm
            modalType={editModalMsg.type}
            formItems={editModalMsg.formItems}
            editSava={editSava}
            onCancelHandle={closeModal}
          ></MyNormForm>
        </div>
      </Modal>
      <ProTable
        actionRef={actionRef}
        bordered
        rowSelection={rowSelection}
        columns={columns}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        request={params => getNormHeavyLuggageList(params)}
        rowKey="id"
        postData={data => data}
        expandedRowRender={expandedRowRender}
        toolBarRender={() => [
          <div className={styles.btnWrapper}>
            <AuthComponent authCode="mkt.heavyLuggage.norm.save">
              <Button type="primary" onClick={addHandle}>
                新建
              </Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.heavyLuggage.norm.update">
              <Button  onClick={editHandle}>
                编辑
              </Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.heavyLuggage.norm.delete">
              <Button  onClick={delHandle}>
                删除
              </Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.heavyLuggage.norm.save">
              <Button  onClick={copyaddHandle}>
                拷贝并新建
              </Button>
            </AuthComponent>
          </div>,
        ]}
      ></ProTable>
    </>
  );
}
export default connect(({ heavyLuggage }) => {
  return {
    placeSelectData: heavyLuggage.placeSelectData,
  };
})(NormTable);
